<?php
use app\admin\model\Menu;
use app\admin\model\Role;
use app\admin\model\Node;

/**
 * 获取菜单权限
 * @return mixed
 */
function getMenus()
{
    $menus = session("menus");
    if ($menus == '') {
        $menus=getAuth();
        session("menus", $menus);

        //按钮权限
        $buttons=getAuth(1);
        $menu_len = count($buttons);
        if ($menu_len > 0) {
            for ($i = 0; $i < $menu_len; $i++) {
                $menuCodes[$i] = $buttons[$i]['code'];
            }
            session("menuCodes", $menuCodes);
        }
    }

    //封装成树对象
    $nodes = treeInit($menus, "");

    foreach ($menus as $temp) {
        $node = $nodes[$temp['id']];
        $pid = $node->getParentId();
        if ($pid != 0) {
            $pnode = $nodes[$node->getParentId()];
            $pc = $pnode->getChildren();
            array_push($pc, $node);
            $pnode->setChildren($pc);
        }
    }

    $resData = "[";
    foreach ($menus as $temp) {
        $node = $nodes[$temp['id']];
        $pid = $node->getParentId();
        if ($pid == 0) {//根节点
            $resData = $resData . $node->toString1() . ",";
        }
    }
    //切割掉最后一个逗号
    $resData = substr($resData, 0, strlen($resData) - 1);

    $resData = $resData . "]";

    if($resData=="]"){
        return json_decode("[]",true);
    }else{
        return json_decode($resData,true);
    }
}

/**
 * 获取权限
 * @param int $type
 * @return array|false|PDOStatement|string|\think\Collection
 */
function getAuth($type=0){
    $menus = [];
    if (session("user")['login_name'] == 'admin') {//超级管理员
        $menus = D("menu")->where("status=0 and type=".$type)->order('sort asc')->select();
    } else {
        //获取用户菜单权限
        $roles = Role::where("id in (" . session("user")['roles'] . ")")->field("menus")->select();
        $role_len = count($roles);
        if ($role_len > 0) {
            for ($i = 0; $i < $role_len; $i++) {
                if ($menus == []) {
                    $menus = $roles[$i]['menus'];
                } else {
                    $menus = $menus . ',' . $roles[$i]['menus'];
                }
            }
            $menus = Menu::where("id in (" . $menus . ")")->order('sort asc')->select();
        }
    }
    return $menus;
}

/**
 * 封装树
 * @param $data
 * @param $checks
 * @return array
 */
function treeInit($data, $checks)
{
    $nodes = array();
    $ids = array();
    if ($checks != "") {
        $ids = explode(',', $checks);
    }

    foreach ($data as $vo) {
        $node = new Node();
        if (in_array($vo['id'], $ids)) {
            $node->setChecked("true");
        }
        $node->setId($vo['id']);
        $node->setText($vo['name']);
        $node->setParentId($vo['pid']);
        $node->setIcon($vo['icon']);
        $node->setType($vo['type']);
        $node->setHref($vo['code']);
        $nodes[$vo['id']] = $node;
    }
    return $nodes;
}

/**
 * 按钮权限判断
 * @param string $rule
 * @return string
 */
function authCheck($rule = "")
{
    $menuCodes = session("menuCodes");
    if (in_array($rule, $menuCodes)) {//有权限
        return '';
    } else {//无权限
        return 'display: none;';
    }
}

/**
 * 获取真实IP
 * @param int $type
 * @return mixed
 */
function get_client_ip($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    /*if($_SERVER['HTTP_X_REAL_IP']){//nginx 代理模式下，获取客户端真实IP
        $ip=$_SERVER['HTTP_X_REAL_IP'];
    }else*/
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) unset($arr[$pos]);
        $ip = trim($arr[0]);
    } else if (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 判断文件夹是否存在不存在则创建
 * @param $dir
 * @param int $mode
 * @return bool
 */
function mkdirs($dir, $mode = 0777)
{
    if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
    if (!mkdirs(dirname($dir), $mode)) return FALSE;
    return @mkdir($dir, $mode);
}

/**
 * 递归删除文件夹
 * @param $dir
 * @param string $file_type
 */
function delFile($dir,$file_type='') {
    if(is_dir($dir)){
        $files = scandir($dir);
        //打开目录 //列出目录中的所有文件并去掉 . 和 ..
        foreach($files as $filename){
            if($filename!='.' && $filename!='..'){
                if(!is_dir($dir.'/'.$filename)){
                    if(empty($file_type)){
                        unlink($dir.'/'.$filename);
                    }else{
                        if(is_array($file_type)){
                            //正则匹配指定文件
                            if(preg_match($file_type[0],$filename)){
                                unlink($dir.'/'.$filename);
                            }
                        }else{
                            //指定包含某些字符串的文件
                            if(false!=stristr($filename,$file_type)){
                                unlink($dir.'/'.$filename);
                            }
                        }
                    }
                }else{
                    delFile($dir.'/'.$filename);
                    rmdir($dir.'/'.$filename);
                }
            }
        }
    }else{
        if(file_exists($dir)) unlink($dir);
    }
}

/**
 * 驼峰模式转换
 * @param $str
 * @param bool $ucfirst
 * @return mixed|string
 */
function convertUnderline($str , $ucfirst = true)
{
    $str = ucwords(str_replace('_', ' ', $str));
    $str = str_replace(' ','',lcfirst($str));
    return $ucfirst ? ucfirst($str) : $str;
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 数组转对象
 * @param $array
 * @return StdClass
 */
function array2object($array) {
    if (is_array($array)) {
        $obj = new StdClass();
        foreach ($array as $key => $val){
            $obj->$key = $val;
        }
    }
    else { $obj = $array; }
    return $obj;
}

/**
 * 对象转数组
 * @param $object
 * @return mixed
 */
function object2array($object) {
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    }
    else {
        $array = $object;
    }
    return $array;
}

/**
 * 生成指定长度的随机码。
 * @param int $length 随机码的长度。
 * @return string
 */
function createRandomCode($length)
{
    $randomCode = "";
    $randomChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    for ($i = 0; $i < $length; $i++) {
        $randomCode .= $randomChars{mt_rand(0, 35)};
    }
    return $randomCode;
}
